package cn.lili.modules.member.serviceimpl;

import cn.lili.cache.Cache;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.RechargeFow;
import cn.lili.modules.member.mapper.MemberMapper;
import cn.lili.modules.member.mapper.RechargeFowMapper;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.RechargeFowService;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawItem;
import cn.lili.modules.wallet.mapper.MemberWalletItemMapper;
import cn.lili.modules.wallet.service.MemberWithdrawItemService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员等级接口业务层实现
 *
 * @author Chopper
 * @since 2021-03-29 14:10:16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RechargeFowServiceImpl extends ServiceImpl<RechargeFowMapper, RechargeFow> implements RechargeFowService {

	@Autowired
	private RechargeFowMapper rechargeFowMapper;

	@Autowired
	private MemberWalletItemMapper memberWithdrawItemMapper;
	/**
	 * 缓存
	 */
	@Autowired
	private Cache cache;

	public IPage<RechargeFow> getRechargeFowPage(RechargeFow rechargeFow, PageVO page) {
		QueryWrapper<RechargeFow> queryWrapper = Wrappers.query();
		// 流水号
		if (rechargeFow.getSn() != null && !rechargeFow.getSn().equals("")) {
			queryWrapper.eq("sn", rechargeFow.getSn());
		}
		// 交易类型
		if (rechargeFow.getRechargeType() != null && !rechargeFow.getRechargeType().equals("")) {
			queryWrapper.eq("recharge_type", rechargeFow.getRechargeType());
		}
		// id
		if (rechargeFow.getId() != null) {
			queryWrapper.eq("a.id", rechargeFow.getId());
		}
		queryWrapper.orderByDesc("create_time");
		return this.baseMapper.getRechargeFowPage(PageUtil.initPage(page), queryWrapper);
	}

	@Override
	public Map<String, Object> updatePromote(String sn, Double price, String memberId, String type) {
		if (null != price && price.compareTo(0D) > 0) {
			Map<String, Object> map = new HashMap<>();
			Double allPrice = price;
			QueryWrapper<RechargeFow> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("member_id", memberId);
			queryWrapper.eq("realization", "0");
			queryWrapper.orderByAsc("add_time");
			List<RechargeFow> rechargeFowList = rechargeFowMapper.selectList(queryWrapper);
			Double alreadyMoney = 0D;// 已扣除现金
			Double alreadyPrice = 0D;// 已扣除焕呗

			if (CollectionUtils.isNotEmpty(rechargeFowList)) {
				for (RechargeFow rechargeFow : rechargeFowList) {
					// 循环出每一次的充值记录
					if (price.compareTo(rechargeFow.getCanHuanBei()) >= 0) {
						// 应扣除焕呗额大于等于可扣除焕呗额，把整条记录都扣完
						alreadyMoney = CurrencyUtil.add(alreadyMoney, rechargeFow.getCanMoney());// 增加已扣除现金
						alreadyPrice = CurrencyUtil.add(alreadyPrice, rechargeFow.getCanHuanBei());// 增加已扣除焕呗
						price = CurrencyUtil.sub(price, rechargeFow.getCanHuanBei());// 应扣除焕呗额减少
						// 插入数据到明细表
						MemberWithdrawItem memberWithdrawItem = new MemberWithdrawItem();
						memberWithdrawItem.setApplyMoney(rechargeFow.getCanHuanBei());
						memberWithdrawItem.setRealMoney(rechargeFow.getCanMoney());
						memberWithdrawItem.setOrderItemId(rechargeFow.getId());
						memberWithdrawItem.setSn(sn);
						memberWithdrawItem.setMemberId(memberId);
						memberWithdrawItem.setFee(rechargeFow.getFee());
						memberWithdrawItem.setType(type);
						memberWithdrawItemMapper.insert(memberWithdrawItem);

						// 修改充值明细表信息
						rechargeFow.setCanMoney(0D);
						rechargeFow.setCanHuanBei(0D);
						rechargeFow.setRealization("-1");
						rechargeFowMapper.updateById(rechargeFow);
					} else {
						// 应扣除焕呗额小于可扣除焕呗额，只扣除一部分
						Double canMoney = CurrencyUtil.mul(price, rechargeFow.getFee());// 扣除现金 = 应扣除焕呗额 * 费率

						alreadyMoney = CurrencyUtil.add(alreadyMoney, canMoney);// 增加已扣除现金
						alreadyPrice = CurrencyUtil.add(alreadyPrice, price);// 增加已扣除焕呗

						// 插入数据到明细表
						MemberWithdrawItem memberWithdrawItem = new MemberWithdrawItem();
						memberWithdrawItem.setApplyMoney(price);// 扣除焕呗
						memberWithdrawItem.setRealMoney(canMoney);// 扣除现金
						memberWithdrawItem.setOrderItemId(rechargeFow.getId());
						memberWithdrawItem.setSn(sn);
						memberWithdrawItem.setMemberId(memberId);
						memberWithdrawItem.setFee(rechargeFow.getFee());
						memberWithdrawItem.setType(type);
						memberWithdrawItemMapper.insert(memberWithdrawItem);

						// 修改充值明细表信息
						rechargeFow.setCanMoney(CurrencyUtil.sub(rechargeFow.getCanMoney(), canMoney));// 剩余现金 = 可扣除现金 -
																										// 扣除现金
						rechargeFow.setCanHuanBei(CurrencyUtil.sub(rechargeFow.getCanHuanBei(), price));// 剩余焕呗额 =
																										// 可扣除焕呗额 -
																										// 扣除焕呗额
						rechargeFowMapper.updateById(rechargeFow);
						price = 0D;
						break;
					}
				}
				// } else {
				// throw new ServiceException(ResultCode.CAN_NOT_BALANCE);
			}
//			map.put("alreadyPrice", alreadyPrice);
			map.put("alreadyPrice", allPrice);
			map.put("alreadyMoney", alreadyMoney);
			map.put("fee", CurrencyUtil.div(alreadyMoney, allPrice));
			map.put("colPrice", CurrencyUtil.sub(allPrice, alreadyMoney));// 手续费
			return map;
		}
		return null;
	}

	@Override
	public Map<String, Object> updatePromoteRefund(String sn, Double price, String memberId, String type) {
		Map<String, Object> map = new HashMap<>();
		QueryWrapper<MemberWithdrawItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("sn", sn);
		queryWrapper.eq("type", type);
		List<MemberWithdrawItem> memberWithdrawItemList = memberWithdrawItemMapper.selectList(queryWrapper);// 所有需要退款的记录
		Double alreadyMoney = 0D;// 已退还现金
		Double alreadyPrice = 0D;// 已退还焕呗

		if (CollectionUtils.isNotEmpty(memberWithdrawItemList)) {
			for (MemberWithdrawItem memberWithdrawItem : memberWithdrawItemList) {
				// 循环出每一次的扣款记录
				// 应扣除焕呗额大于等于可扣除焕呗额，把整条记录都扣完
				alreadyMoney = CurrencyUtil.add(alreadyMoney, memberWithdrawItem.getRealMoney());// 增加已退还现金
				alreadyPrice = CurrencyUtil.add(alreadyPrice, memberWithdrawItem.getApplyMoney());// 增加已退还焕呗
				price = CurrencyUtil.sub(price, memberWithdrawItem.getApplyMoney());// 应扣除焕呗额减少

				// 修改充值明细表信息
				RechargeFow rechargeFow = rechargeFowMapper.selectById(memberWithdrawItem.getOrderItemId());
				rechargeFow.setCanMoney(
						CurrencyUtil.add(rechargeFow.getCanMoney().compareTo(0D) == 0 ? 0D : rechargeFow.getCanMoney(),
								memberWithdrawItem.getRealMoney()));
				rechargeFow.setCanHuanBei(CurrencyUtil.add(
						rechargeFow.getCanHuanBei().compareTo(0D) == 0 ? 0D : rechargeFow.getCanHuanBei(),
						memberWithdrawItem.getApplyMoney()));
				rechargeFow.setRealization("0");
				rechargeFowMapper.updateById(rechargeFow);

			}
			// }else {
			// throw new ServiceException("退回失败");
		}
		map.put("alreadyPrice", alreadyPrice);
		map.put("alreadyMoney", alreadyMoney);
		return map;
	}

}